package com.seguriapp.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class Util {

  private static final String REST_DATE_FORMAT = "ddMMyyyy HH:mm:ss";
  private static final String WEB_DATE_FORMAT = "dd/MM/yyyy HH:mm:ss";
  public static final String ROLE_BY_DEFECT = "ROLE_USER";
  // public static final String DESTINATION_DIR_PATH = "/usuarios/seguriapp/uploaded/temp";
  public static final String DESTINATION_DIR_PATH = "C:\\test\\temp";

  public static String parseDateToString(final Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat(REST_DATE_FORMAT);
    if (date == null) {
      return null;
    } else {
      return sdf.format(date);
    }
  }

  public static String parseDateToWebString(final Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat(WEB_DATE_FORMAT);
    if (date == null) {
      return null;
    } else {
      return sdf.format(date);
    }
  }

  public static Date parseStringToDate(final String dateStr) {
    SimpleDateFormat sdf = new SimpleDateFormat(REST_DATE_FORMAT);
    if (dateStr != null) {
      try {
        return sdf.parse(dateStr);
      } catch (ParseException e) {
        return null;
      }
    }
    return null;
  }

  /**
   * Encrypt the password using the MessageDigest |
   * 
   * @param text
   *          unencrypted password
   * @return encrypted password
   */
  public static String encodeString(String text) {
    String pwd = null;
    try {
      MessageDigest sha = MessageDigest.getInstance("MD5");
      byte[] result = sha.digest(text.getBytes());
      pwd = new String(hexEncode(result));
    } catch (NoSuchAlgorithmException e) {
    }
    return pwd;
  }

  /**
   * Convert bytes to hexadecimal String representation
   * 
   * @param aInput
   *          input
   * @return hexadecimal code
   */
  public static String hexEncode(byte[] aInput) {
    StringBuffer result = new StringBuffer();
    char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    for (int idx = 0; idx < aInput.length; ++idx) {
      byte b = aInput[idx];
      result.append(digits[(b & 0xf0) >> 4]);
      result.append(digits[b & 0x0f]);
    }
    return result.toString();
  }

  /**
   * Gets a random alphanumeric string
   * 
   * @param length
   *          string length
   * @return random string
   */

  public static String randomString(int len) {
    String ab = "0123456789abcdefghijklmnopqrstuvwxyz";
    Random rnd = new Random();
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
      sb.append(ab.charAt(rnd.nextInt(ab.length())));
    }
    return sb.toString();
  }

}
